﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class StateCoverFormReport : Form
    {
        public StateCoverFormReport()
        {
            InitializeComponent();
        }

        int avpID, regID, canalID = 0, drID = 0, year, kv;

        bool IsCanal = true;

        private void StateCoverFormReport_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }
            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());
            year = Convert.ToInt32(cbYear.Text);
            for (int i = 0; i < 4; i++)
            {
                cbKvartal.Items.Add((i + 1).ToString() + " Квартал");
            }
            cbKvartal.SelectedIndex = 0;

            rbCanal.Checked = true;
        }

        private void rbCanal_CheckedChanged(object sender, EventArgs e)
        {
            chbCanal.Enabled = cbKvartal.Enabled = rbCanal.Checked;
            IsCanal = true;
            chbDrainage.Checked = false;
        }

        private void rbDrainage_CheckedChanged(object sender, EventArgs e)
        {
            chbDrainage.Enabled = rbDrainage.Checked;
            IsCanal = false;
            chbCanal.Checked = false;
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                cbCanal.SelectedIndexChanged -= cbCanal_SelectedIndexChanged;
                cbCanal.DataSource = DBClass.Canals
                    .Where(wh => wh.AVPID == avpID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbCanal.DisplayMember = "Name";
                cbCanal.ValueMember = "ID";
                cbCanal.SelectedIndex = -1;
                cbCanal.Text = string.Empty;
                cbCanal.SelectedIndexChanged += new EventHandler(cbCanal_SelectedIndexChanged);

                cbDrainage.SelectedIndexChanged -= cbDrainage_SelectedIndexChanged;
                cbDrainage.DataSource = DBClass.Drainages
                    .Where(wh => wh.AVPID == avpID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbDrainage.DisplayMember = "Name";
                cbDrainage.ValueMember = "ID";
                cbDrainage.SelectedIndex = -1;
                cbDrainage.Text = string.Empty;
                cbDrainage.SelectedIndexChanged += new EventHandler(cbDrainage_SelectedIndexChanged);
            }
        }

        private void cbCanal_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCanal.SelectedIndex >= 0)
            {
                canalID = Convert.ToInt32(cbCanal.SelectedValue);
            }
        }

        private void cbDrainage_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbDrainage.SelectedIndex >= 0)
            {
                drID = Convert.ToInt32(cbDrainage.SelectedValue);
            }
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbYear.SelectedIndex >= 0)
            {
                year = Convert.ToInt32(cbYear.Text);
            }
        }

        private void cbKvartal_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbKvartal.SelectedIndex >= 0)
            {
                kv = cbKvartal.SelectedIndex;
            }
        }

        private void chbAVP_CheckedChanged(object sender, EventArgs e)
        {
            cbAVP.Enabled = chbAVP.Checked;
        }

        private void chbCanal_CheckedChanged(object sender, EventArgs e)
        {
            cbCanal.Enabled = chbCanal.Checked;
        }

        private void chbDrainage_CheckedChanged(object sender, EventArgs e)
        {
            cbDrainage.Enabled = chbDrainage.Checked;
        }

        private void chbDate_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            int? aId, wID, y;
            DateTime? dt;

            if (IsCanal)
            {

                if (chbAVP.Checked && avpID > 0)
                {
                    aId = avpID;
                }
                else
                    aId = null;

                if (chbCanal.Checked && canalID > 0)
                {
                    wID = canalID;
                }
                else
                    wID = null;

                if (chbDate.Checked && year > 0 && kv >= 0)
                {
                    dt = new DateTime(year, kv * 3 + 1, 1);
                }
                else
                    dt = null;

                dgvCoverState.DataSource = DBClass.RESPContext.CanalCoverStateReport(aId, wID, dt);

            }
            else
            {
                if (chbAVP.Checked && avpID > 0)
                {
                    aId = avpID;
                }
                else
                    aId = null;

                if (chbCanal.Checked && drID > 0)
                {
                    wID = drID;
                }
                else
                    wID = null;

                if (chbDate.Checked && year > 0)
                {
                    y = year;
                }
                else
                    y = null;

                dgvCoverState.DataSource = DBClass.RESPContext.DraingeCoverStateReport(aId, wID, y);
            }

            if (InformationClass.Lang)
            {
                dgvCoverState.Columns["Name"].HeaderText = "Наименование";
                dgvCoverState.Columns["CoverType"].HeaderText = "Тип русла";
                dgvCoverState.Columns["Length"].HeaderText = "Протяженность (км)";
                dgvCoverState.Columns["BadLength"].HeaderText = "В неуд. состоянии (км)";
                dgvCoverState.Columns["Note"].HeaderText = "Примечание";
            }
            else
            {
                dgvCoverState.Columns["Name"].HeaderText = "номи";
                dgvCoverState.Columns["CoverType"].HeaderText = "Ўзан тури";
                dgvCoverState.Columns["Length"].HeaderText = "Узунлиги (км)";
                dgvCoverState.Columns["BadLength"].HeaderText = "Жумладан, қониқарсиз ҳолатда(км)";
                dgvCoverState.Columns["Note"].HeaderText = "Изоҳ";
            }

            for (int i = 0; i < dgvCoverState.RowCount; i++)
            {
                dgvCoverState.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }

            dgvCoverState.AutoResizeColumns();
        }

        private void dgvCoverState_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvCoverState.Columns.Contains("CoverType"))
            {
                if (e.ColumnIndex.Equals(dgvCoverState.Columns["CoverType"].Index) && e.Value != null)
                {
                    e.Value = UtilClass.GetCategoryDisplayName((int)e.Value, "ChannelType");
                }
            }
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;
        Workbooks excelappworkbooks;

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvCoverState.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();

                excelworksheet.Select(1);
                excelapp.Visible = true;
            }
        }

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i8r10.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i8r10uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

            excelworksheet.Cells.NumberFormat = "@";

            if (chbDate.Checked)
            {
                string str = "Период ";
                if (rbCanal.Checked)
                    str += cbKvartal.Text;
                str += " " + cbYear.Text + " Года";

                excelworksheet.Cells[6, 2] = str;

            }

            if (cbRegion.SelectedIndex >= 0)
                excelworksheet.Cells[4, 3] = cbRegion.Text;

            for (int i = 0; i < dgvCoverState.Rows.Count; i++)
            {
                for (int j = 0; j < dgvCoverState.Columns.Count; j++)
                {
                    excelworksheet.Cells[i + 9, dgvCoverState.Columns[j].DisplayIndex + 4] = dgvCoverState[j, i].FormattedValue;
                    addBorder(excelworksheet.Cells[i + 9, dgvCoverState.Columns[j].DisplayIndex + 4]);
                }
                // добавить район и авп
                string avpName = string.Empty;
                if (rbCanal.Checked)
                    avpName = UtilClass.GetAVPNameCanal((string)dgvCoverState["Name", i].Value).ToString();
                else
                    avpName = UtilClass.GetAVPNameDrainage((string)dgvCoverState["Name", i].Value).ToString();
                excelworksheet.Cells[i + 9, 3] = avpName;
                addBorder(excelworksheet.Cells[i + 9, 4]);
                excelworksheet.Cells[i + 9, 2] = i + 1;
                addBorder(excelworksheet.Cells[i + 9, 2]);
            }
            excelworksheet.Columns.AutoFit();
            excelworksheet.Rows.AutoFit();
        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvCoverState.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvCoverState);
        }

    }
}
